using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using System;
using System.Collections.Generic;
using System.Linq;
using Urs.Admin.Models.Agents;
using Urs.Admin.Models.Stores;
using Urs.Data.Domain.Agents;
using Urs.Data.Domain.Configuration;
using Urs.Data.Domain.Stores;
using Urs.Framework.Controllers;
using Urs.Framework.Kendoui;
using Urs.Services.Agents;
using Urs.Services.Localization;
using Urs.Services.Media;
using Urs.Services.Security;
using Urs.Services.Stores;

namespace Urs.Admin.Controllers
{
    [AdminAuthorize]
    public partial class AgentGoodsController : BaseAdminController
    {
        #region Fields

        private readonly IAgentProductService _service;
        private readonly IPermissionService _permissionService;
        private readonly ILocalizationService _localizationService;
        private readonly ICategoryService _categoryService;
        private readonly IBrandService _brandService;
        private readonly IGoodsService _goodsService;
        private readonly AdminAreaSettings _adminAreaSettings;
        private readonly IPictureService _pictureService;

        #endregion Fields

        #region Constructors
        public AgentGoodsController(IAgentProductService service,
            IPermissionService permissionService,
            ILocalizationService localizationService,
            ICategoryService categoryService,
            IBrandService brandService,
            IGoodsService goodsService,
            AdminAreaSettings adminAreaSettings,
            IPictureService pictureService)
        {
            this._service = service;
            this._permissionService = permissionService;
            this._localizationService = localizationService;
            this._categoryService = categoryService;
            this._brandService = brandService;
            this._goodsService = goodsService;
            this._adminAreaSettings = adminAreaSettings;
            this._pictureService = pictureService;
        }
        #endregion

        #region Util


        [NonAction]
        private void PrepareProductPictureModel(GoodsModel model, Goods goods)
        {
            if (model == null)
                throw new ArgumentNullException("model");

            if (goods != null)
            {
                var defaultProductPicture = _pictureService.GetPicturesByGoodsId(goods.Id, 1).FirstOrDefault();
                model.PictureThumbnailUrl = _pictureService.GetPictureUrl(defaultProductPicture, 200, true);
            }
        }

        #endregion

        #region List

        public IActionResult Index()
        {
            return RedirectToAction("List");
        }
        public IActionResult List()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageAgents))
                return HttpUnauthorized();

            var model = new GoodsListModel();
            //categories
            model.AvailableCategories.Add(new SelectListItem() { Text = _localizationService.GetResource("Admin.Common.All"), Value = "0" });
            foreach (var c in _categoryService.GetAllCategories(showHidden: true))
                model.AvailableCategories.Add(new SelectListItem() { Text = c.GetCategoryNameWithPrefix(_categoryService), Value = c.Id.ToString() });

            //brands
            model.AvailableBrands.Add(new SelectListItem() { Text = _localizationService.GetResource("Admin.Common.All"), Value = "0" });
            foreach (var m in _brandService.GetAll(true))
                model.AvailableBrands.Add(new SelectListItem() { Text = m.Name, Value = m.Id.ToString() });

            model.PublishedStatus.Add(new SelectListItem() { Text = "--全部--", Value = 0.ToString() });
            model.PublishedStatus.Add(new SelectListItem() { Text = "--已发布--", Value = 1.ToString() });
            model.PublishedStatus.Add(new SelectListItem() { Text = "--未发布--", Value = 2.ToString() });
            return View(model);
        }
        [HttpPost]
        public IActionResult List(PageRequest command, GoodsListModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageAgents))
                return HttpUnauthorized();

            var gridModel = new ResponseResult();

            var categoryIds = new List<int>();
            if (model.SearchCategoryId > 0)
                categoryIds.Add(model.SearchCategoryId);
            var list = _goodsService.SearchGoodss(out IList<int> filterableSpecificationAttributeOptionIds, true,
                categoryIds.ToArray(), brandId: model.SearchBrandId, keywords: model.SearchName,
                orderBy: GoodsSortingEnum.Position, pageIndex: command.Page - 1, pageSize: command.Limit, showHidden: true, sku: model.SearchSku);

            var ids = list.Select(q => q.Id).ToList();

            var agnetProducts = _service.GetListByProductIds(ids.ToArray());

            gridModel.data = list.Select(x =>
            {
                var apModel = new AgentGoodsModel();
                apModel.ProductId = x.Id;
                apModel.ProductName = x.Name;
                apModel.Sku = x.Sku;
                apModel.Price = PriceFormatter.FormatPrice(x.Price);
                var ap = agnetProducts.FirstOrDefault(q => q.ProductId == x.Id);
                if (ap != null)
                {
                    apModel.Rate = ap.Rate;
                    apModel.ParentRate = ap.ParentRate;
                }
                return apModel;
            });
            gridModel.count = list.TotalCount;
            return Json(gridModel);
        }

        [HttpPost]
        public IActionResult Update(AgentGoodsModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageAgents))
                return HttpUnauthorized();
            var entity = _service.GetById(model.ProductId);

            if (entity != null)
            {
                entity.Rate = model.Rate;
                entity.ParentRate = model.ParentRate;
                _service.Update(entity);
            }
            else
            {
                entity = new AgentGoods()
                {
                    ProductId = model.ProductId,
                    Rate = model.Rate,
                    ParentRate = model.ParentRate
                };
                _service.Insert(entity);
            }
            return Json(new { success = 1 });
        }

        #endregion

    }
}

